`include "sdr_head.v"

module sdr_ref(
    input                   clk,
    input                   ref_en,
    output reg              ref_done,
    output      [19 : 0]    ref_bus
);

    localparam  st0 = 3'd0;
    localparam  st1 = 3'd1;
    localparam  st2 = 3'd2;
    localparam  st3 = 3'd3;
    localparam  st4 = 3'd4;

    reg [12 : 0]    sdr_a;
    reg [1  : 0]    sdr_ba;
    reg [2  : 0]    state;
    reg [14 : 0]    cnt;
    reg [3  : 0]    cmd;
    reg             sdr_cke;

    assign ref_bus = {sdr_cke, cmd, sdr_a, sdr_ba};

    always @(posedge clk)
    begin
        if (!ref_en) begin
            cmd <= `NOP;
            sdr_cke <= 1'b1;
            ref_done <= 1'b0;
            sdr_a <= 13'b0;
            sdr_ba <= 2'b0;
            cnt <= 15'b0;
            state <= st0;
        end
        else begin
            case (state)
                st0 : begin
                    cmd <= `PRE;
                    sdr_a[10] <= 1'b1;
                    state <= st1;
                end
                st1 : begin
                    cmd <= `NOP;
                    state <= st2;
                end
                st2 : begin
                    cmd <= `REF;
                    state <= st3;
                end
                st3 : begin
                    cmd <= `NOP;
                    if (cnt < `TRFC)
                        cnt <= cnt + 1'b1;
                    else begin
                        cnt <= 15'b0;
                        ref_done <= 1'b1;
                        state <= st4;
                    end
                end
                st4 : begin
                    ref_done <= 1'b0;
                    state <= st4;
                end
                default : state <= st4;
            endcase
        end
    end

endmodule 